#! /usr/bin/bash

usage() {
    echo "Usage: $0 [0~100]/[i]"
    echo "       Set the master volume in percent to the specified value."
    echo "       If no volume value is specified, turn the sound off if"
    echo "       the sound is on, or make it 50% if it is off."
    echo "       The subcommand 'i' is for interactive usage."
    exit 0
}

adjust_with_retreat_print() {
    amixer set Master ${CUR_VOLUME}% > /dev/null
    printf "\033[u\033[K\x1b[38;2;255;100;0m%s%%\x1b[0m\n" $CUR_VOLUME
}

# CUR_VOLUME=$(amixer get Master | grep -oE "(0|[1-9][0-9]*)%" | head -n1 | tr -d '%')
CUR_VOLUME=$(amixer get Master | "$HOME/opt/percent-reader")
PAT="0|([1-9][0-9]*)"

if [ $# -eq 0 ]
then
    printf "\x1b[38;2;100;100;255m%s\x1b[0m: \x1b[38;2;255;100;0m%s%%\x1b[0m\n" 'Current volume' $CUR_VOLUME
    exit 0
elif [[ $1 = 'i' ]]
then
    printf "j: -1, J: -10\nk: +1, K: +10\nm: mute/unmute\nq: quit\n"
    printf "\x1b[38;2;100;100;255m%s\x1b[0m: \033[s\x1b[38;2;255;100;0m%s%%\x1b[0m\n" 'Current volume' $CUR_VOLUME
    read -srn 1 inp
    while [ "$inp" != 'q' ]
    do
        case $inp in
            'm')
                if [ $CUR_VOLUME -gt 0 ]
                then
                    CUR_VOLUME=0
                else
                    CUR_VOLUME=50
                fi
                adjust_with_retreat_print
                ;;
            'j')
                if [ $CUR_VOLUME -gt 0 ]; then
                    CUR_VOLUME=$((CUR_VOLUME - 1))
                    adjust_with_retreat_print
                fi
                ;;
            'k')
                if [ $CUR_VOLUME -lt 100 ]
                then
                    CUR_VOLUME=$((CUR_VOLUME + 1))
                    adjust_with_retreat_print
                fi
                ;;
            'J')
                if [ $CUR_VOLUME -gt 10 ]; then
                    CUR_VOLUME=$((CUR_VOLUME - 10))
                else
                    CUR_VOLUME=0
                fi
                adjust_with_retreat_print
                ;;
            'K')
                if [ $CUR_VOLUME -lt 90 ]; then
                    CUR_VOLUME=$((CUR_VOLUME + 10))
                else
                    CUR_VOLUME=100
                fi
                adjust_with_retreat_print
                ;;
        esac
        read -srn 1 inp
    done

    exit 0
elif [[ $1 =~ $PAT && $1 -ge 0 && $1 -le 100 ]]
then
    VOLUME_PRECENT=$1
else
    usage
fi

amixer set Master ${VOLUME_PRECENT}%
